package org.wendu.wdoa.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.wendu.wdoa.common.CurrentUser;
import org.wendu.wdoa.common.OaConstants;
import org.wendu.wdoa.common.Result;
import org.wendu.wdoa.common.token.TokenUser;
import org.wendu.wdoa.common.token.TokenUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/*
 令牌认证过滤器
 */
@Slf4j
public class TokenVerifyFilter extends BasicAuthenticationFilter {
    public TokenVerifyFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    public TokenVerifyFilter(AuthenticationManager authenticationManager, AuthenticationEntryPoint authenticationEntryPoint) {
        super(authenticationManager, authenticationEntryPoint);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        try {
            //从请求头中获取令牌
            String clientToken = request.getHeader(OaConstants.HEADER_NAME_TOKEN);
            log.debug("令牌=========================={}",clientToken);
            //校验令牌,没通过则表现异常
            TokenUser tokenUser = TokenUtils.verify(clientToken);

            //验证通过,自定义认证信息(永远放行)

            CurrentUser principal = new CurrentUser(clientToken,null,clientToken); //创建当事人
            String credentials = clientToken;

            //创建认证信息
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(principal,credentials);

            //将认证信息放入安全上下文中
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            chain.doFilter(request,response); //继续向后过滤



        } catch (Exception e) {

            Result error = Result.err(Result.CODE_ERR_UNLOGINED,e.getMessage());

            ObjectMapper objectMapper = new ObjectMapper();
            String jsonStr = objectMapper.writeValueAsString(error);


            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print(jsonStr);
            out.flush();
            out.close();


        }


    }
}
